// 回溯，剪枝
class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        if (candidates.size() == 0) {
            return {};
        }

        sort(candidates.begin(), candidates.end());
        int len = candidates.size();
        vector<bool> used(len, false);
        dfs(candidates, used, target, 0);
        
        return res;
    }

private:
    vector<vector<int>> res;
    vector<int> path;
    // vector<bool> used;

    void dfs(vector<int>& candidates, vector<bool>& used, int target, int startIndex) {
        if (target < 0) {
            return;
        }
        if (target == 0) {
            res.push_back(path);
            return;
        }
        if (startIndex == candidates.size()) {
            return;
        }

        for (int i = startIndex; i < candidates.size(); ++i) {
            if (i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]) {
                continue;
            }
            path.push_back(candidates[i]);
            used[i] = true;
            dfs(candidates, used, target - candidates[i], i + 1);
            used[i] = false;
            path.pop_back();
        }
    }
};
